import { MaterialIcons } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import React, { useState } from "react";
import {
  Alert,
  FlatList,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";

interface PuzzlePhotoSelectorProps {
  onImagesSelect: (images: string[]) => void;
  onVideosSelect: (videos: string[]) => void;
  maxCount?: number;
}

interface MediaItem {
  id: string;
  uri: string;
  type: "image" | "video";
  selected: boolean;
}

export const PuzzlePhotoSelector: React.FC<PuzzlePhotoSelectorProps> = ({
  onImagesSelect,
  onVideosSelect,
  maxCount = 10,
}) => {
  const [mediaItems, setMediaItems] = useState<MediaItem[]>([]);
  const [selectedItems, setSelectedItems] = useState<MediaItem[]>([]);
  const [activeTab, setActiveTab] = useState<"album" | "camera">("album");

  // 从相册选择图片
  const pickImagesFromAlbum = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsMultipleSelection: true,
        quality: 0.8,
      });

      if (!result.canceled && result.assets) {
        const newItems: MediaItem[] = result.assets.map((asset, index) => ({
          id: `album_${Date.now()}_${index}`,
          uri: asset.uri,
          type: asset.type === "video" ? "video" : "image",
          selected: false,
        }));

        setMediaItems(prev => [...prev, ...newItems]);
      }
    } catch (error) {
      Alert.alert("错误", "无法访问相册");
    }
  };

  // 拍照或录像
  const takePhotoOrVideo = async () => {
    try {
      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        quality: 0.8,
      });

      if (!result.canceled && result.assets && result.assets[0]) {
        const asset = result.assets[0];
        const newItem: MediaItem = {
          id: `camera_${Date.now()}`,
          uri: asset.uri,
          type: asset.type === "video" ? "video" : "image",
          selected: false,
        };

        setMediaItems(prev => [newItem, ...prev]);
      }
    } catch (error) {
      Alert.alert("错误", "无法访问相机");
    }
  };

  // 处理媒体项选择
  const handleItemSelect = (item: MediaItem) => {
    if (selectedItems.length >= maxCount && !item.selected) {
      Alert.alert("提示", `最多只能选择${maxCount}个文件`);
      return;
    }

    const updatedItems = mediaItems.map(mediaItem =>
      mediaItem.id === item.id
        ? { ...mediaItem, selected: !mediaItem.selected }
        : mediaItem
    );

    setMediaItems(updatedItems);
    
    const newSelectedItems = updatedItems.filter(item => item.selected);
    setSelectedItems(newSelectedItems);
  };

  // 确认选择
  const handleConfirmSelection = () => {
    const selectedImages = selectedItems
      .filter(item => item.type === "image")
      .map(item => item.uri);
    
    const selectedVideos = selectedItems
      .filter(item => item.type === "video")
      .map(item => item.uri);

    if (selectedImages.length > 0) {
      onImagesSelect(selectedImages);
    }
    
    if (selectedVideos.length > 0) {
      onVideosSelect(selectedVideos);
    }

    // 清空选择
    setSelectedItems([]);
    setMediaItems(prev => prev.map(item => ({ ...item, selected: false })));
  };

  // 渲染媒体项
  const renderMediaItem = ({ item }: { item: MediaItem }) => (
    <TouchableOpacity
      style={[
        styles.mediaItem,
        item.selected && styles.mediaItemSelected,
      ]}
      onPress={() => handleItemSelect(item)}
    >
      <Image source={{ uri: item.uri }} style={styles.mediaImage} />
      
      {/* 视频标识 */}
      {item.type === "video" && (
        <View style={styles.videoIndicator}>
          <MaterialIcons name="play-circle-outline" size={20} color="#fff" />
        </View>
      )}
      
      {/* 选择标识 */}
      {item.selected && (
        <View style={styles.selectionIndicator}>
          <MaterialIcons name="check-circle" size={24} color="#007AFF" />
        </View>
      )}
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>
      {/* 标签页 */}
      <View style={styles.tabContainer}>
        <TouchableOpacity
          style={[styles.tab, activeTab === "album" && styles.activeTab]}
          onPress={() => setActiveTab("album")}
        >
          <MaterialIcons 
            name="photo-library" 
            size={20} 
            color={activeTab === "album" ? "#007AFF" : "#666"} 
          />
          <Text style={[styles.tabText, activeTab === "album" && styles.activeTabText]}>
            相册
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.tab, activeTab === "camera" && styles.activeTab]}
          onPress={() => setActiveTab("camera")}
        >
          <MaterialIcons 
            name="camera-alt" 
            size={20} 
            color={activeTab === "camera" ? "#007AFF" : "#666"} 
          />
          <Text style={[styles.tabText, activeTab === "camera" && styles.activeTabText]}>
            相机
          </Text>
        </TouchableOpacity>
      </View>

      {/* 内容区域 */}
      <View style={styles.content}>
        {/* 操作按钮 */}
        <View style={styles.actionButtons}>
          <TouchableOpacity style={styles.actionButton} onPress={pickImagesFromAlbum}>
            <MaterialIcons name="photo-library" size={24} color="#007AFF" />
            <Text style={styles.actionButtonText}>选择照片</Text>
          </TouchableOpacity>
          
          <TouchableOpacity style={styles.actionButton} onPress={takePhotoOrVideo}>
            <MaterialIcons name="camera-alt" size={24} color="#007AFF" />
            <Text style={styles.actionButtonText}>拍照/录像</Text>
          </TouchableOpacity>
        </View>

        {/* 媒体列表 */}
        {mediaItems.length > 0 ? (
          <FlatList
            data={mediaItems}
            renderItem={renderMediaItem}
            keyExtractor={(item) => item.id}
            numColumns={5}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.mediaGrid}
          />
        ) : (
          <View style={styles.emptyState}>
            <MaterialIcons name="photo-library" size={48} color="#ccc" />
            <Text style={styles.emptyStateText}>暂无照片</Text>
            <Text style={styles.emptyStateSubtext}>点击上方按钮选择照片</Text>
          </View>
        )}
      </View>

      {/* 确认按钮 */}
      {selectedItems.length > 0 && (
        <TouchableOpacity style={styles.confirmButton} onPress={handleConfirmSelection}>
          <Text style={styles.confirmButtonText}>
            确定 ({selectedItems.length}/{maxCount})
          </Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    maxHeight: 300,
    backgroundColor: "#f5f5f5",
  },
  tabContainer: {
    flexDirection: "row",
    backgroundColor: "#fff",
    paddingHorizontal: 15,
    paddingTop: 15,
  },
  tab: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 12,
    borderBottomWidth: 2,
    borderBottomColor: "transparent",
    marginRight: 24,
  },
  activeTab: {
    borderBottomColor: "#007AFF",
  },
  tabText: {
    marginLeft: 4,
    fontSize: 14,
    color: "#666",
  },
  activeTabText: {
    color: "#007AFF",
    fontWeight: "600",
  },
  content: {
    flex: 1,
  },
  actionButtons: {
    flexDirection: "row",
    padding: 15,
    backgroundColor: "#fff",
    marginBottom: 10,
  },
  actionButton: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#f0f8ff",
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 8,
    marginRight: 12,
  },
  actionButtonText: {
    marginLeft: 8,
    fontSize: 14,
    color: "#007AFF",
    fontWeight: "500",
  },
  mediaGrid: {
    paddingHorizontal: 10,
  },
  mediaItem: {
    width: "20%",
    aspectRatio: 1,
    marginBottom: 8,
    padding: 0,
    borderRadius: 6,
    overflow: "hidden",
    position: "relative",
  },
  mediaItemSelected: {
    borderWidth: 3,
    borderColor: "#007AFF",
  },
  mediaImage: {
    width: "100%",
    height: "100%",
  },
  videoIndicator: {
    position: "absolute",
    top: 8,
    right: 8,
    backgroundColor: "rgba(0,0,0,0.5)",
    borderRadius: 12,
    padding: 4,
  },
  selectionIndicator: {
    position: "absolute",
    top: 8,
    left: 8,
    backgroundColor: "#fff",
    borderRadius: 12,
  },
  emptyState: {
    alignItems: "center",
    justifyContent: "center",
    padding: 40,
  },
  emptyStateText: {
    fontSize: 16,
    color: "#666",
    marginTop: 12,
  },
  emptyStateSubtext: {
    fontSize: 14,
    color: "#999",
    marginTop: 4,
  },
  confirmButton: {
    backgroundColor: "#007AFF",
    paddingVertical: 12,
    paddingHorizontal: 20,
    margin: 15,
    borderRadius: 8,
    alignItems: "center",
  },
  confirmButtonText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "600",
  },
});
